﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace AttendanceDataInteraction
{
    public class AttendanceManager
    {
        public AttendanceManager()
        {
            clinet = new MyTCPClient("192.168.0.157", 31344);
            if (System.Configuration.ConfigurationManager.AppSettings["IPAddress"] != null)
            {
                string address = System.Configuration.ConfigurationManager.AppSettings["IPAddress"].ToString().Trim();
                string ip = address.Split(':')[0];
                int port = Convert.ToInt32(address.Split(':')[1]);
                clinet = new MyTCPClient(ip, port);
            }
            
            clinet.DataRecv += clinet_DataRecv;
        }

        byte[] buffer = new byte[1024 * 10240];
        int index = 0;
        MyTCPClient clinet = null;
        
        public List<AttendanceEntity> GetAttendance(DateTime startTime, DateTime endTime)
        {
            List<AttendanceEntity> list = null;
           if( !clinet.ConnectStatus)
           {
               index = 0;
               clinet.Connect();
               clinet.SendData(AttendanceCommand.RequestLogin());
               System.Threading.Thread.Sleep(500);
               clinet.SendData(AttendanceCommand.RequestGetAttendance(startTime, endTime));
               System.Threading.Thread.Sleep(3000);
               clinet.Disconnect();
               list=ProcessData(buffer);
           }
           return list;
        }

        void clinet_DataRecv(byte[] data)
        {
            Buffer.BlockCopy(data, 0,buffer, index,data.Length);
            index += data.Length;
        }

        List<AttendanceEntity> ProcessData(byte[] buf)
        {
            AttendanceResponseProtocal pro = new AttendanceResponseProtocal();
            List<AttendanceEntity> list = new List<AttendanceEntity>();
            for (int i = 0; i < buf.Length; )
            {
                if ((buf[i + 8] == 127) && (buf[i + 9] == 2) && (buf[i + 10] == 12))
                {
                    break;
                }
                if (buf[i + 10] != 114)
                {
                    i += buf[i + 10];
                    continue;
                }
                if ((buf[i + 8] == 1) && (buf[i + 9] == 2))
                {
                    byte[] temp = new byte[buf[i + 10]];
                    Buffer.BlockCopy(buf, i, temp, 0, temp.Length);
                    pro.BufferData = temp;
                    list.Add(pro.ParseProtocal());
                    i += buf[i + 10];
                    continue;
                }
            }
            return list;
        }
    }
}
